<template>
  <div class="user-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>用户管理</span>
          <el-button type="primary" @click="handleAdd">添加用户</el-button>
        </div>
      </template>
      
      <el-table :data="users" style="width: 100%">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="username" label="用户名" />
        <el-table-column prop="email" label="邮箱" />
        <el-table-column prop="phone" label="手机号" />
        <el-table-column label="角色" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.isAdmin === 1 ? 'warning' : 'info'">
              {{ scope.row.isAdmin === 1 ? '管理员' : '用户' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加用户' : '编辑用户'"
      width="500px"
    >
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="dialogType === 'add'">
          <el-input v-model="form.password" type="password" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone" />
        </el-form-item>
        <el-form-item label="用户类型" prop="isAdmin">
          <el-select v-model="form.isAdmin">
            <el-option label="普通用户" :value="0" />
            <el-option label="管理员" :value="1" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'

export default {
  name: 'UserManagement',
  setup() {
    const users = ref([])
    const dialogVisible = ref(false)
    const dialogType = ref('add')
    const formRef = ref(null)

    const form = reactive({
      username: '',
      password: '',
      email: '',
      phone: '',
      isAdmin: 0 // 默认为普通用户
    })

    const validatePhone = (rule, value, callback) => {
      if (!value) {
        callback();
        return;
      }
      const phoneRegex = /^1[3-9]\d{9}$/;
      if (!phoneRegex.test(value)) {
        callback(new Error('请输入正确的11位手机号码'));
      } else {
        callback();
      }
    };

    const rules = {
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' }
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' }
      ],
      phone: [
        { required: false },  // 手机号可以为空
        { min: 11, max: 11, message: '手机号必须是11位', trigger: 'blur' },
        { validator: validatePhone, trigger: 'blur' }
      ]
    }

    const loadUsers = async () => {
      try {
        const res = await request.get('/admin/user/list')
        users.value = res.data
      } catch (error) {
        console.error('Failed to load users:', error)
      }
    }

    const handleAdd = () => {
      dialogType.value = 'add'
      dialogVisible.value = true
      form.username = ''
      form.password = ''
      form.email = ''
      form.phone = ''
    }

    const handleEdit = (row) => {
      dialogType.value = 'edit'
      dialogVisible.value = true
      Object.assign(form, row)
    }

    const handleDelete = (row) => {
      ElMessageBox.confirm('确定要删除该用户吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await request.delete(`/admin/users/${row.id}`)
          ElMessage.success('删除成功')
          loadUsers()
        } catch (error) {
          console.error('Failed to delete user:', error)
        }
      })
    }

    const handleSubmit = () => {
      formRef.value.validate(async (valid) => {
        if (valid) {
          try {
            // 添加手机号唯一性校验
            if (form.phone) {
              // 如果是编辑模式，传入用户ID避免与自身冲突
              const userId = dialogType.value === 'edit' ? form.id : null;
              const phoneExists = await checkPhoneExists(form.phone, userId);
              if (phoneExists) {
                return; // 如果手机号已存在，终止后续操作
              }
            }
            
            // 校验通过后继续提交表单
            if (dialogType.value === 'add') {
              await request.post('/auth/register', form);
            } else {
              await request.put(`/admin/users/${form.id}`, form);
            }
            
            ElMessage.success(dialogType.value === 'add' ? '添加成功' : '编辑成功');
            dialogVisible.value = false;
            loadUsers();
          } catch (error) {
            console.error('Failed to submit:', error);
            ElMessage.error('操作失败');
          }
        }
      });
    };

    const checkPhoneExists = async (phone, userId = null) => {
      try {
        // 从已加载的用户列表中检查手机号是否存在
        const phoneExists = users.value.some(user => 
          user.phone === phone && user.id !== userId
        );
        
        if (phoneExists) {
          ElMessage.error('该手机号已被其他用户使用');
          return true;
        }
        return false;
      } catch (error) {
        console.error('检查手机号失败:', error);
        return false;
      }
    };

    loadUsers()

    return {
      users,
      dialogVisible,
      dialogType,
      form,
      formRef,
      rules,
      handleAdd,
      handleEdit,
      handleDelete,
      handleSubmit,
      checkPhoneExists
    }
  }
}
</script>

<style scoped>
.user-management {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>